package com.fiehn.util.dbunit;

import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: pradeep
 * Date: Mar 3, 2010
 * Time: 1:55:51 PM
 * This is the Connection utility to create connections and close connections also.
 */

public class DBConnection {

    private static Connection conn;
    private static Logger oslogger = Logger.getLogger("DBConnection");

    /**
     * This mathod is used to get the sql connection
     * @return Connection
     * @throws Exception
     */
    public static Connection getConnection() throws Exception
	{
		try
        {
            String url = "jdbc:postgresql://bbtest.fiehnlab.ucdavis.edu:5432/compound-repository-test";
            String driverClassName = "org.postgresql.Driver";
            String username = "compound";
            String password = "asdf";

            Class.forName(driverClassName);
            conn = DriverManager.getConnection(url, username, password);

		}catch (Exception ce)
		{
			oslogger.error("Exception in getConnection Mathod of DBConnection Class : ",ce);
			ce.printStackTrace();
			throw ce;
		 }
	   return conn;
	}

    /**
     *  Close the Connection
     */
    public static void closeConnection()
    {
        try
        {
            if(!conn.isClosed())
                conn.close();
        }
        catch(SQLException sqlex)
        {
            oslogger.error("Not able to close connection  " , sqlex);
        }
    }

    /**
     * close the given connection instence 
     * @param con
     */
    public static void closeConnection(Connection con)
    {
        try
        {
            if(con != null && !con.isClosed())
            {
                con.close();
                con = null;
            }
        }
        catch(SQLException sqlex)
        {
            oslogger.error("Sql exception While Closing the connection  ", sqlex);
        }
        catch(Exception genExp)
        {
            oslogger.error("General exception Not able to close connection  ", genExp);
        }
    }
    

}
